package com.prs.crm.service.project.impl;

import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.context.Constrains;
import com.prs.crm.dao.project.TaskTransmitDao;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.domain.project.TaskTransmit;
import com.prs.crm.exception.InValidException;
import com.prs.crm.service.impl.SimpleFlowServiceImpl;
import com.prs.crm.service.project.TaskTransmitService;

public class TaskTransmitServiceImpl extends SimpleFlowServiceImpl<TaskTransmit,TaskTransmitDao> implements TaskTransmitService{


	public void createTransmit(TaskTransmit transmit,boolean audit)
	{
		TaskTransmit exttrans = this.getDao().findTransmit(transmit.getTask(), 
									Constrains.TASKTRANSMIT_STATE_INIT);
		if (exttrans!=null)
		{
			throw new InValidException("尚有未处理的任务转发");
		}
		if (audit)
		{
			transmit.setStatus(Constrains.TASKTRANSMIT_STATE_INIT);
			this.startFlow(transmit);
		}
		else
		{
			transmit.setStatus(Constrains.TASKTRANSMIT_STATE_VALID);
			transmit.getTask().setExecutor(transmit.getReciver());
		}
		super.save(transmit);
	}
	
	public void startFlow(TaskTransmit entity)
	{
		this.save(entity);
		validateSubmit(entity);
		if (entity.getTask().getParent()!=null)
			entity.setVerifer(entity.getTask().getParent().getExecutor());
		else
			entity.setVerifer(entity.getTask().getProject().getRecorder());

		super.startFlow(entity);
	}
	
	
	@Override
	public void validateSubmit(TaskTransmit entity)
	{
		
	}
	
	public PaginationSupport listTransmitHistory(PaginationSupport page,Person recorder)
	{
		DetachedCriteria criteria =  this.createQuery(TaskTransmit.class);
		criteria.add(Restrictions.eq("recorder", recorder))
				.add(Restrictions.ne("status",Constrains.TASKTRANSMIT_STATE_INIT));
		page.setOrders(new Order[]{Order.asc("id")});
		return super.listByPage(criteria, page);
	}
	
	@Override
	public void onFlowEnd(TaskTransmit entity)
	{
		/**
		 * 如果通过了审核，则任务执行状态为完成
		 */
		if (entity.getFlowstatus()==Constrains.WORKFLOWENTITY_STATE_VALID)
		{
			entity.setStatus(Constrains.TASKTRANSMIT_STATE_VALID);
			entity.getTask().setExecutor(entity.getReciver());
		}
		else
		{
			entity.setStatus(Constrains.TASKTRANSMIT_STATE_INVALID);
		}
		super.save(entity);
	}
}
